import json
from django.http import HttpResponse


from entity.common.response import ResponseData, ResponseStatus
from userApp.service.upload.oss import upload_file
from userApp.service.user.userservice import UserService

from utils.transfer import transferToJson


userService = UserService()
def getUserInfo(request):
    user = request.session.get('user')
    response = ResponseData(True,ResponseStatus.SUCESS,"",user)
    return HttpResponse(transferToJson(response),content_type=ResponseData.JSON_CONTENT_TYPE)

def changeUserInfo(request):
    response = None
    if request.method == 'POST':
        user = json.loads(request.body)['user']
        name = json.loads(request.session.get('user'))['name']
        user = userService.changeUserInfo(name,user)
        request.session['user'] = transferToJson(user)
        response = ResponseData(True,ResponseStatus.SUCESS,"更改成功",user)
    else:
        response = ResponseData(False,ResponseStatus.RESPONSE_FAIL,"",[])
    return HttpResponse(transferToJson(response),content_type=ResponseData.JSON_CONTENT_TYPE)

def uploadImg(request):
    response=None
    if request.method == 'POST':
        print(request.FILES)
        file = request.FILES['img']
        if not  file:
            response = ResponseData(False,ResponseStatus.PARAMETER_ERROR,"上传失败",[])
        else:
            user = request.session['user']
            fileUrl= upload_file(user['name'],file)
            user['img']=fileUrl
            userService.upateImg(user)
            # 保存到数据库中
            response = ResponseData(True,ResponseStatus.SUCESS,"上传成功",{'img':fileUrl})
    return HttpResponse(transferToJson(response),content_type=ResponseData.JSON_CONTENT_TYPE)